package com.itheima.common;

import lombok.Data;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 通用返回结果，服务端响应的数据最终都会封装成此对象
 *
 * @param <T>
 */
@Data
public class CommonResult<T> implements Serializable {

    private Integer code; //编码：1成功，0和其它数字为失败
    private String msg; //错误信息
    private T data; //数据
    private Map map = new HashMap(); //动态数据

    public static <T> CommonResult<T> ok(T object) {
        CommonResult<T> r = new CommonResult<T>();
        r.data = object;
        r.code = 200;
        return r;
    }

    //未登录
    public static <T> CommonResult<T> unauthorized(String msg) {
        CommonResult r = new CommonResult();
        r.msg = msg;
        r.code = 401;
        return r;
    }

    //没有权限
    public static <T> CommonResult<T> forbidden(String msg) {
        CommonResult r = new CommonResult();
        r.msg = msg;
        r.code = 403;
        return r;
    }

    public static <T> CommonResult<T> error(String msg) {
        CommonResult r = new CommonResult();
        r.msg = msg;
        r.code = 404;
        return r;
    }

    public CommonResult<T> add(String key, Object value) {
        this.map.put(key, value);
        return this;
    }

}
